
import axios from 'axios'
import router from '../router'
import qs from 'qs'
import { BASE_URL } from "./config";
import { ElMessage } from 'element-plus'
// let timer: any = null
axios.defaults.baseURL = BASE_URL
//  ctx.headers = {
//         Accept: 'application/json',
//         Authorization: JSON.parse(localStorage.getItem('userCode')) || '',
//         ...ctx.headers,
//       }
axios.interceptors.request.use((config: any) => {
  config.headers = {
    token: localStorage.getItem('token') || '',
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  }
  if (config.method == 'post') {
    config.data = qs.stringify(config.data, {
      allowDots: true,
    })
  }
  // config.timer = setTimeout(() => {
  //   Toast.loading({
  //     message: '加载中...',
  //     forbidClick: true,
  //   });
  //   timer = null;
  // }, 1000);
  return Promise.resolve(config);
})
axios.interceptors.response.use((res: any) => {
  // clearTimeout(res.config.timer)
  // res.config.timer = null
  const { code, message } = res.data
  if (res.config.url == '/userCert/photo') {
    return res.data
  }
  if (typeof res.data !== 'object') {
    return Promise.reject(res)
  }
  if (code != 200) {
    console.log(ElMessage)
    ElMessage.warning(message)
    // ElMessage.warning({
    //   message: content,
    //   type: 'warning'
    // });
    if (code == 405 || code == 403) {
      router.replace('Login')
      localStorage.removeItem('token')
    }
    return Promise.reject(res.data)
  }

  return res.data
})

export default axios
